﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Http.WebSockets;
using TouchSocket.Sockets;
using WebSocketServer.WebSocketService.Message;
using WebSocketServer.WebSocketService.MessageHandlers;

namespace WebSocketServer.WebSocketService.Plugins
{
    public class RecieveMessagePlugin : PluginBase, IWebSocketReceivedPlugin
    {
        private readonly ILog m_logger;
        private MessageHandlerManager messageHandlerManager;
        public RecieveMessagePlugin(ILog logger)
        {
            this.m_logger = logger;
            messageHandlerManager = new MessageHandlerManager();
        }
        public async Task OnWebSocketReceived(IWebSocket socket, WSDataFrameEventArgs e)
        {
            switch (e.DataFrame.Opcode)
            {
                case WSDataType.Cont:
                    m_logger.Info($"收到中间数据，长度为：{e.DataFrame.PayloadLength}");

                    return;

                case WSDataType.Text:
                    m_logger.Info(e.DataFrame.ToText());
                    
                    var message=JsonConvert.DeserializeObject<WebSocketData>(e.DataFrame.ToText());
                    await  messageHandlerManager.HandleMessageAsync(socket, message!);
                    if (!socket.Client.IsClient)
                    {
                      await  socket.SendAsync("我已收到");
                    }
                    return;

                case WSDataType.Binary:
                    if (e.DataFrame.FIN)
                    {
                        m_logger.Info($"收到二进制数据，长度为：{e.DataFrame.PayloadLength}");
                    }
                    else
                    {
                        m_logger.Info($"收到未结束的二进制数据，长度为：{e.DataFrame.PayloadLength}");
                    }
                    return;

                case WSDataType.Close:
                    {
                        m_logger.Info("远程请求断开");
                        socket.Close("断开");
                    }
                    return;

                case WSDataType.Ping:
                    break;

                case WSDataType.Pong:
                    break;

                default:
                    break;
            }

            await e.InvokeNext();
        }
    }
}
